package com.example.pyphone3;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.io.InputStream;

public class AliyunOssUtil {
    @Autowired
    AliyunOssProperties properties;
    /**
     * 向aliyun 推送单文件    MultipartFile
     * @return
     */
    public boolean pushSingleFile(MultipartFile file, String fileName) {
        OSSClient client=null;
        InputStream inputStream= null;
        try {
//            inputStream = file.getInputStream();
            String keyid=properties.getAccessKeyId();
            String keysecret=properties.getAccessKeySecret();
            String url =properties.getEndPoint();
            String BucketName=properties.getBacketName();

            client=new OSSClient(url,keyid,keysecret);
            if (!(client.doesBucketExist(BucketName))){
                // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。DBF5FB6CB011EFC69CBAE89970540D5E
                client.createBucket(BucketName);  //当为空，创建一个Bucket
            }
            PutObjectResult result= client.putObject(BucketName,fileName,inputStream);
            System.out.println(result.getETag());
        } finally {
            if(client!=null){
                client.shutdown();
            }
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public String getProperties(){
        return this.properties.getBacketName()+"---"+this.properties.getAccessKeyId()+"---"+this.properties.getAccessKeySecret();
    }

    public String imgUrl(){
        return this.properties.getImgUrl();
    }


}
